package com.changgou.oauth.service.impl;

import com.changgou.oauth.service.AuthService;
import com.changgou.oauth.util.AuthToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Base64;
import java.util.Map;

/**
 * @Author tang.qingbo
 * @Date 2020/9/4 14:31
 * @Version 1.0
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private RestTemplate restTemplate;

    /***
     * 授权认证方法
     * @param username
     * @param password
     * @param clientId
     * @param clientSecret
     */
    @Override
    public AuthToken login(String username, String password, String clientId, String clientSecret) {
        //密码授权认证请求地址
        String reqPath = "http://localhost:9001/oauth/token";

        //header参数封装
        String headerParam = getHeaderParam(clientId, clientSecret);
        MultiValueMap<String, String> header = new LinkedMultiValueMap<>();
        header.set("Authorization", headerParam);

        //封装请求体body的参数
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.set("grant_type", "password");
        body.set("username", username);
        body.set("password", password);

        ResponseEntity<Map> exchange = restTemplate.exchange(reqPath, HttpMethod.POST, new HttpEntity<>(body, header), Map.class);
        Map map = exchange.getBody();
        String accessToken = map.get("access_token").toString();
        String refreshToken = map.get("refresh_token").toString();
        String jti = map.get("jti").toString();

        AuthToken authToken = new AuthToken();
        authToken.setAccessToken(accessToken);
        authToken.setRefreshToken(refreshToken);
        authToken.setJti(jti);
        return authToken;
    }

    /**
     * 封装header参数信息
     */
    private String getHeaderParam(String clientId, String clientSecret) {
        //拼接客户端id和客户端秘钥
        String authorization = clientId + ":" + clientSecret;
        //进行base64加密
        byte[] encodeHeader = Base64.getEncoder().encode(authorization.getBytes());
        //转换为字符串并返回
        return "Basic " + new String(encodeHeader);
    }
}
